/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is product of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.admin.client.subcomponents;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.elf.gwt.admin.client.AdminComponentController;
import com.elf.gwt.admin.client.components.CurrenciesAdministrationComponent;
import com.elf.gwt.admin.client.components.EditOrderComponent;
import com.elf.gwt.admin.client.components.OrderStatusComponent;
import com.elf.gwt.admin.client.components.ProductSearchComponent;
import com.elf.gwt.admin.client.components.TaxClassesComponent;
import com.elf.gwt.admin.client.components.TermsAndConditionsComponent;
import com.elf.gwt.common.client.callback.SubComponentCallback;
import com.elf.gwt.common.client.model.AddressModel;
import com.elf.gwt.common.client.model.AttributeValueModel;
import com.elf.gwt.common.client.model.DownloadModel;
import com.elf.gwt.common.client.model.OrderMetaModel;
import com.elf.gwt.common.client.model.OrderModel;
import com.elf.gwt.common.client.model.OrderPaymentModel;
import com.elf.gwt.common.client.model.OrderProductModel;
import com.elf.gwt.common.client.model.OrderStatusHistoryModel;
import com.elf.gwt.common.client.model.OrderStatusModel;
import com.elf.gwt.common.client.model.OrderTotalModel;
import com.elf.gwt.common.client.model.TaxClassModel;
import com.elf.gwt.common.client.model.TermsAndConditionsModel;
import com.elf.gwt.common.client.utils.CommonUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;

/**
 *
 */
public class EditOrderSubComponent extends AdminSubComponent
{	
	protected EditOrderComponent component;
	protected OrderMetaModel orderMetaModel;
	protected OrderModel orderModel;
	protected static OrderStatusComponent orderStatusComponent = null;
	protected static TaxClassesComponent taxClassesComponent = null;
	protected String type;

	protected HashMap<String, Widget> elements = null;

	protected String action = "";
	protected DialogBox addressDialogBox = null;
	protected DialogBox productDialogBox = null;
	protected DialogBox totalDialogBox = null;
	protected DialogBox paymentDialogBox = null;
	protected DialogBox termsAndConditionsDialogBox = null;

	public EditOrderSubComponent(EditOrderComponent component, AdminComponentController controller, String handle, SubComponentCallback callback)
	{
		super(controller, handle, null, callback);
		this.component = component;
		if (this.type == null) this.type = EditOrderComponent.DETAILS;
		orderMetaModel = component.getOrderMetaModel();
		orderModel = component.getOrderModel();
		elements = new HashMap<String, Widget>();
		if (currenciesAdministrationComponent == null) currenciesAdministrationComponent = (CurrenciesAdministrationComponent)controller.getComponent("CurrenciesAdministrationComponent");
		if (orderStatusComponent == null) orderStatusComponent = (OrderStatusComponent)controller.getComponent("OrderStatusComponent");
		if (taxClassesComponent == null) taxClassesComponent = (TaxClassesComponent)controller.getComponent("TaxClassesComponent");
	}
	public void build()
	{
		build(false);
	}

	public void build(boolean editIntroduction)
	{
		boolean isQuote = false;
		if (orderModel.getStatusId() < 0) isQuote = true;

		boolean edit = false;
		if (orderModel.getStatusId() < orderMetaModel.getDoNotEditStatusId() && type.equals(EditOrderComponent.DETAILS)) edit = true;

		clear();
		elements = new HashMap<String, Widget>();
		if (!type.equals(EditOrderComponent.DETAILS)) {
			String storeNameAddress = controller.getStoreNameAddress();
			int index = storeNameAddress.indexOf("Copyright");
			if (index > -1)	storeNameAddress = storeNameAddress.substring(0, index);
			HTML storeNameAddressHTML = new HTML(storeNameAddress);
			storeNameAddressHTML.setStyleName("StoreNameAddress");
			Image logoImage = new Image(this.getImageDirectory() + "logo.png");
			Grid gridHeader = new Grid(1, 2);
			gridHeader.setWidget(0, 0, storeNameAddressHTML);
			gridHeader.setWidget(0, 1, logoImage);
			gridHeader.setWidth("97%");
			gridHeader.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT);
			gridHeader.getCellFormatter().setVerticalAlignment(0, 1, HasVerticalAlignment.ALIGN_TOP);
			add(gridHeader);
		}

		String orderLabelPrefix = "Order Id: ";
		if (isQuote) orderLabelPrefix = "Quote Id: ";
		Label orderLabel = new Label(orderLabelPrefix + orderModel.getId());
		orderLabel.setStyleName("Title");
		add(orderLabel);

		String purchaseDatePrefix = "Purchase Date: ";
		if (orderModel.getStatusId() == 0) purchaseDatePrefix = "Order Date: ";
		else if (isQuote) purchaseDatePrefix = "Quote Date: ";
		Label purchaseDateLabel = new Label(purchaseDatePrefix + DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_SHORT).format(orderModel.getDatePurchased()));
		purchaseDateLabel.setStyleName("Title");
		add(purchaseDateLabel);

		if (isQuote) {
			String introduction = orderModel.getQuoteIntroduction();

			if (!editIntroduction && introduction != null && introduction.length() > 0) {
				add (new HTML("<br/>" + introduction));
			}
			if (type.equals(EditOrderComponent.DETAILS)) {
				if (editIntroduction) {

					TextArea introductionTextArea = new TextArea();
					introductionTextArea.setCharacterWidth(100);
					introductionTextArea.setVisibleLines(20);
					if (introduction != null) {
						introductionTextArea.setText(orderModel.getQuoteEditIntroduction());
					}
					add (introductionTextArea);
					elements.put("quoteIntroduction", introductionTextArea);

					HorizontalPanel hintroductionPanel = new HorizontalPanel();
					add(new HTML("&nbsp;"));
					Button cancelIntroductionButton = new Button("cancel", cancelEditIntroductionHandler);
					hintroductionPanel.add(cancelIntroductionButton);
					hintroductionPanel.add(new InlineHTML("&nbsp;&nbsp;"));
					Button editIntroductionButton = new Button("save", editIntroductionHandler);
					hintroductionPanel.add(editIntroductionButton);
					add(hintroductionPanel);

				}
				else {
					String introductionButtonText = "add introduction";
					if (introduction != null && introduction.length() > 0) introductionButtonText = "update introduction";
					add(new HTML("&nbsp;"));
					Button editIntroductionButton = new Button(introductionButtonText, openEditIntroductionHandler);
					add(editIntroductionButton);
				}
			}
		}

		add(new HTML("&nbsp;"));

		int columns = 3;
		if (isQuote) columns = 1;
		int rows = 2;
		if (edit) rows++;
		if (type.equals(EditOrderComponent.PACKING_SLIP)) columns = 2;
		Grid gridCustomer = new Grid(rows,columns);

		gridCustomer.setWidth("97%");
		gridCustomer.getRowFormatter().addStyleName(0, "TableHeader");
		gridCustomer.getRowFormatter().setVerticalAlign(1, HasVerticalAlignment.ALIGN_TOP);

		String customerHeading = "Customer";
		if (type.equals(EditOrderComponent.DETAILS)) customerHeading += " (Id: " + orderModel.getAccountModel().getId() + ")";
		gridCustomer.setText(0, 0, customerHeading);

		String address = "";
		if (orderMetaModel.isDisplayCompany() && orderModel.getCompany() != null && orderModel.getCompany().length() > 0) 
			address += orderModel.getCompany() + "<br/>";
		address += orderModel.getName() + "<br/>";
		address += orderModel.getStreet() + "<br/>";
		if (orderMetaModel.isDisplaySuburb())  address += orderModel.getSuburb() + "<br/>";
		if (orderMetaModel.isDisplayState())
			address += orderModel.getCity() + ", " + orderModel.getState() + " " + orderModel.getPostcode() + "<br/>";
		else
			address += orderModel.getCity() + ", " + orderModel.getPostcode() + "<br/>";
		address += orderModel.getCountry() + "<br/>";
		address += orderModel.getTelephone() + "<br/>";
		address += orderModel.getEmailAddress() + "<br/>";
		gridCustomer.setHTML(1, 0, address);
		if (edit) {
			Image editCustomerIcon = new Image(getImageCommonDirectory() + "edit_icon.gif");
			editCustomerIcon.setStyleName("ComponentLink");
			editCustomerIcon.addClickHandler(editCustomerHandler);
			gridCustomer.setWidget(2, 0, editCustomerIcon);
		}
		if (!isQuote)
		{
			gridCustomer.setText(0, 1, "Shipping Address");
			address = "";
			if (orderMetaModel.isDisplayCompany() && orderModel.getShipToCompany() != null && orderModel.getShipToCompany().length() > 0) 
				address += orderModel.getShipToCompany() + "<br/>";
			address += orderModel.getShipToName() + "<br/>";
			address += orderModel.getShipToStreet() + "<br/>";
			if (orderMetaModel.isDisplaySuburb())  address += orderModel.getShipToSuburb() + "<br/>";
			if (orderMetaModel.isDisplayState())
				address += orderModel.getShipToCity() + ", " + orderModel.getShipToState() + " " + orderModel.getShipToPostcode() + "<br/>";
			else
				address += orderModel.getShipToCity() + ", " + orderModel.getShipToPostcode() + "<br/>";
			address += orderModel.getShipToCountry() + "<br/>";
			gridCustomer.setHTML(1, 1, address);
			if (edit) {
				Image editShipToIcon = new Image(getImageCommonDirectory() + "edit_icon.gif");
				editShipToIcon.setStyleName("ComponentLink");
				editShipToIcon.addClickHandler(editShipToHandler);
				gridCustomer.setWidget(2, 1, editShipToIcon);
			}

			if (!type.equals(EditOrderComponent.PACKING_SLIP)) {
				gridCustomer.setText(0, 2, "Billing Address");
				address = "";
				if (orderMetaModel.isDisplayCompany() && orderModel.getBillToCompany() != null && orderModel.getBillToCompany().length() > 0)
					address += orderModel.getBillToCompany() + "<br/>";
				address += orderModel.getBillToName() + "<br/>";
				address += orderModel.getBillToStreet() + "<br/>";
				if (orderMetaModel.isDisplaySuburb())  address += orderModel.getBillToSuburb() + "<br/>";
				if (orderMetaModel.isDisplayState())
					address += orderModel.getBillToCity() + ", " + orderModel.getBillToState() + " " + orderModel.getBillToPostcode() + "<br/>";
				else
					address += orderModel.getBillToCity() + ", " + orderModel.getBillToPostcode() + "<br/>";
				address += orderModel.getBillToCountry() + "<br/>";
				gridCustomer.setHTML(1, 2, address);
				if (edit) {
					Image editBillToIcon = new Image(getImageCommonDirectory() + "edit_icon.gif");
					editBillToIcon.setStyleName("ComponentLink");
					editBillToIcon.addClickHandler(editBillToHandler);
					gridCustomer.setWidget(2, 2, editBillToIcon);
				}
			}
		}

		add(gridCustomer);
		if (!isQuote && orderModel.getPayments().size() < 1) {
			add(new HTML("&nbsp;"));
			add(new InlineHTML("<strong>Payment Method:</strong> " + orderModel.getPaymentMethod()));
		}
		add(new HTML("&nbsp;"));

		List<OrderProductModel> products = orderModel.getProducts();
		int numProducts = products.size();

		columns = 6;
		if (type.equals(EditOrderComponent.PACKING_SLIP)) columns = 4;
		if (type.equals(EditOrderComponent.DETAILS)) columns = columns + 2;

		Grid gridProduct = new Grid(numProducts+1, columns);

		gridProduct.getRowFormatter().addStyleName(0, "TableHeader");
		CellFormatter cf = gridProduct.getCellFormatter();
		gridProduct.setWidth("97%");
		int colnum = 0;
		gridProduct.setText(0, colnum++, "Qty");
		gridProduct.setText(0, colnum++, "");
		gridProduct.setText(0, colnum++, "Product");
		gridProduct.setText(0, colnum++, "Model");
		if (!type.equals(EditOrderComponent.PACKING_SLIP)) {
			gridProduct.setText(0, colnum++, "Price");
		}
		if (type.equals(EditOrderComponent.DETAILS)) {
			gridProduct.setText(0, colnum++, "Tax");
		}
		if (!type.equals(EditOrderComponent.PACKING_SLIP)) {
			gridProduct.setText(0, colnum++, "Total");
		}

		NumberFormat fmt = NumberFormat.getCurrencyFormat(currenciesAdministrationComponent.getCurrencyModel().getCode());
		double currencyValue = currenciesAdministrationComponent.getCurrencyModel().getValue();

		for (int i = 0; i< numProducts; i++)
		{
			colnum = 0;
			int row = i + 1;
			int k = row % 2;
			String rowStyle = "Even";
			if (k > 0) rowStyle = "Odd";
			gridProduct.getRowFormatter().addStyleName(row, rowStyle);	

			gridProduct.getRowFormatter().setVerticalAlign(row, HasVerticalAlignment.ALIGN_TOP);
			OrderProductModel product = products.get(i);

			gridProduct.setText(row, colnum, String.valueOf(product.getQuantity()));
			gridProduct.getCellFormatter().setHorizontalAlignment(row, colnum++, HasHorizontalAlignment.ALIGN_RIGHT);
			gridProduct.setText(row, colnum, String.valueOf(" X "));
			cf.setHorizontalAlignment(row, colnum++, HasHorizontalAlignment.ALIGN_CENTER);

			String strProduct =  product.getName();
			int numAttributes = product.getAttributes().size();
			for (int j = 0; j< numAttributes; j++)
			{
				AttributeValueModel attribute = product.getAttributes().get(j);
				strProduct += "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;" + attribute.getAttributeName() + ": " + attribute.getName();
			}

			if (type.equals(EditOrderComponent.DETAILS)) {
				int numDownloads = product.getDownloads().size();
				for (int j = 0; j< numDownloads; j++)
				{
					DownloadModel download = product.getDownloads().get(j);
					strProduct += "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;download: status: " + download.getStatus() +
					"<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cnt: " + download.getCount() + ", days: " + 
					download.getDays() + ", filename: " +download.getFilename();
				}
			}
			gridProduct.setHTML(row, colnum, strProduct);
			cf.setWordWrap(row, colnum++, false);
			gridProduct.setHTML(row, colnum++, product.getModel());

			if (!type.equals(EditOrderComponent.PACKING_SLIP)) {
				gridProduct.setText(row, colnum, fmt.format(currencyValue * product.getFinalPrice()));
				cf.setHorizontalAlignment(row, colnum++, HasHorizontalAlignment.ALIGN_RIGHT);
			}

			if (type.equals(EditOrderComponent.DETAILS)) {
				gridProduct.setText(row, colnum, fmt.format((product.getTax() * product.getQuantity() * currencyValue * product.getFinalPrice())/100.00));
				cf.setHorizontalAlignment(row, colnum++, HasHorizontalAlignment.ALIGN_RIGHT);
			}

			if (!type.equals(EditOrderComponent.PACKING_SLIP)) {
				gridProduct.setText(row, colnum, fmt.format(product.getQuantity() * currencyValue * product.getFinalPrice()));
				cf.setHorizontalAlignment(row, colnum++, HasHorizontalAlignment.ALIGN_RIGHT);
			}

			if (edit)
			{
				HorizontalPanel toolsPanel = new HorizontalPanel();
				gridProduct.setWidget(row, colnum, toolsPanel);
				cf.setHorizontalAlignment(row, colnum++, HasHorizontalAlignment.ALIGN_CENTER);

				Image editIcon = new Image(getImageCommonDirectory() + "edit_icon.gif");
				editIcon.setStyleName("ComponentLink");
				editIcon.addStyleName("index:" + i);
				editIcon.addClickHandler(editProductHandler);
				toolsPanel.add(editIcon);
				toolsPanel.add(new InlineHTML("&nbsp;"));
				Image deleteIcon = new Image(getImageCommonDirectory() + "delete_icon.gif");
				deleteIcon.setStyleName("ComponentLink");
				deleteIcon.addStyleName("index:" + product.getOpId());
				deleteIcon.addClickHandler(deleteProductHandler);
				toolsPanel.add(deleteIcon);
			}
		}

		add(gridProduct);

		if (edit) {
			HorizontalPanel productButtons = new HorizontalPanel();
			Button addCatalogProductButton = new Button("add catalog product", addCatalogProductHandler);
			productButtons.add(addCatalogProductButton);
			productButtons.add(new InlineHTML("&nbsp;&nbsp;"));
			Button addNonCatalogProductButton = new Button("add non-catalog product", addNonCatalogProductHandler);
			productButtons.add(addNonCatalogProductButton);
			productButtons.add(new InlineHTML("&nbsp;&nbsp;"));
			Button updateCatalogProductsToCurrentPricingButton = new Button("update catalog products to current pricing", updateCatalogProductsToCurrentPricingHandler);
			productButtons.add(updateCatalogProductsToCurrentPricingButton);
			add(productButtons);
		}

		boolean boolCoupon = true;

		double totalValue = 0.0;

		if (!type.equals(EditOrderComponent.PACKING_SLIP)) {
			List<OrderTotalModel> totals = orderModel.getTotals();
			int numTotals = totals.size();
			int numColumns = 2;
			if (type.equals(EditOrderComponent.DETAILS)) numColumns = 3;
			Grid gridTotals = new Grid(numTotals,numColumns);
			gridTotals.setWidth("97%");
			cf = gridTotals.getCellFormatter();
			for (int i = 0; i< numTotals; i++)
			{
				OrderTotalModel total = totals.get(i);
				String title = total.getTitle();
				String error = total.getError();
				String totalClass = total.getTotalClass();
				if (error != null && error.length() > 0) title = "<span class=\"WarningLabel\">" + title + "</span>";
				gridTotals.setHTML(i,0,title);
				cf.setHorizontalAlignment(i, 0, HasHorizontalAlignment.ALIGN_RIGHT);
				String totalLabel = CommonUtils.priceDisplay(currenciesAdministrationComponent.getCurrencyModel(), total.getValue());
				gridTotals.setHTML(i,1,totalLabel);
				cf.setHorizontalAlignment(i, 1, HasHorizontalAlignment.ALIGN_RIGHT);
				cf.setWidth(i,0, "100%");
				if (totalClass.equals("ot_coupon")) boolCoupon = false;
				if ((type.equals(EditOrderComponent.DETAILS)) && (totalClass.equals("ot_adhoc") || totalClass.equals("ot_coupon")))
				{
					Image deleteIcon = new Image(getImageCommonDirectory() + "delete_icon.gif");
					deleteIcon.setStyleName("ComponentLink");
					deleteIcon.addStyleName("index:" + total.getId());
					deleteIcon.addClickHandler(deleteTotalHandler);

					gridTotals.setWidget(i, 2, deleteIcon);
				}
				if (totalClass.equals("ot_total")) totalValue = total.getValue();
			}
			add(gridTotals);
		}
		if (type.equals(EditOrderComponent.DETAILS)) {
			Grid addTotalGrid = new Grid(1,1);
			HorizontalPanel totalButton = new HorizontalPanel();
			Button addTotalButton = new Button("add", addTotalHandler);
			totalButton.add(addTotalButton);
			if (boolCoupon && edit) {
				Button addCouponButton = new Button("add coupon", addTotalCouponHandler);
				totalButton.add(new InlineHTML("&nbsp;&nbsp;"));
				totalButton.add(addCouponButton);
			}
			addTotalGrid.setWidget(0, 0, totalButton);
			addTotalGrid.setWidth("97%");
			addTotalGrid.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_RIGHT);
			add(addTotalGrid);
		}

		if (!type.equals(EditOrderComponent.PACKING_SLIP)) {

			add(new HTML("&nbsp;"));

			List<OrderPaymentModel> payments = orderModel.getPayments();
			int numPayments = payments.size();
			if (numPayments > 0)
			{
				int numColumns = 3;
				if (type.equals(EditOrderComponent.DETAILS)) numColumns = 4;
				Grid gridPayments = new Grid(numPayments+3,numColumns);
				gridPayments.getRowFormatter().addStyleName(0, "TableHeader");
				cf = gridPayments.getCellFormatter();

				gridPayments.setText(0, 0, "Payment Date");
				cf.setWordWrap(0, 0, false);
				gridPayments.setText(0, 1, "Comments");
				gridPayments.setText(0, 2, "Payment Amount");
				cf.setWordWrap(0, 2, false);
				gridPayments.setWidth("97%");
				double totalAmount = 0.0;
				for (int i = 0; i< numPayments; i++)
				{
					int row = i + 1;
					int k = row % 2;
					String rowStyle = "Even";
					if (k > 0) rowStyle = "Odd";
					gridPayments.getRowFormatter().addStyleName(row, rowStyle);	

					OrderPaymentModel payment = payments.get(i);
					Date timestamp = payment.getTimestamp();
					String comments = payment.getComments();
					double amount = payment.getAmount();
					totalAmount += amount;

					gridPayments.setText(row, 0, DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_TIME_SHORT).format(timestamp));
					cf.setWordWrap(row, 0, false);

					gridPayments.setText(row,1,comments);
					cf.setWidth(0, 1, "100%");

					String amountLabel = CommonUtils.priceDisplay(currenciesAdministrationComponent.getCurrencyModel(), amount);
					gridPayments.setHTML(row,2,amountLabel);
					cf.setHorizontalAlignment(row, 2, HasHorizontalAlignment.ALIGN_RIGHT);
					cf.setWordWrap(row, 2, false);
				}
				int row = numPayments + 1;
				gridPayments.setText(row,1,"Total:");
				cf.setHorizontalAlignment(row, 1, HasHorizontalAlignment.ALIGN_RIGHT);
				cf.setWidth(0, 1, "100%");

				String amountLabel = CommonUtils.priceDisplay(currenciesAdministrationComponent.getCurrencyModel(), totalAmount);
				gridPayments.setHTML(row,2,amountLabel);
				cf.setHorizontalAlignment(row, 2, HasHorizontalAlignment.ALIGN_RIGHT);
				cf.setWordWrap(row, 2, false);

				row++;
				gridPayments.setText(row,1,"Amount Due:");
				cf.setHorizontalAlignment(row, 1, HasHorizontalAlignment.ALIGN_RIGHT);
				cf.setWidth(0, 1, "100%");

				amountLabel = CommonUtils.priceDisplay(currenciesAdministrationComponent.getCurrencyModel(), totalValue - totalAmount);
				gridPayments.setHTML(row,2,amountLabel);
				cf.setHorizontalAlignment(row, 2, HasHorizontalAlignment.ALIGN_RIGHT);
				cf.setWordWrap(row, 2, false);

				add(gridPayments);
			}
			if (type.equals(EditOrderComponent.DETAILS)) {
				Grid addPaymentGrid = new Grid(1,1);
				Button addPaymentButton = new Button("add payment", addPaymentHandler);
				addPaymentGrid.setWidget(0, 0, addPaymentButton);
				addPaymentGrid.setWidth("97%");
				addPaymentGrid.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_RIGHT);
				add(addPaymentGrid);
			}
		}

		if (type.equals(EditOrderComponent.DETAILS))
		{
			add(new HTML("&nbsp;"));

			List<OrderStatusHistoryModel> histories = orderModel.getHistories();
			int numHistories = histories.size();
			Grid gridHistories = new Grid(numHistories+1, 4);
			gridHistories.setWidth("97%");
			gridHistories.getRowFormatter().addStyleName(0, "TableHeader");
			cf = gridHistories.getCellFormatter();
			gridHistories.setText(0, 0, "Date Added");
			gridHistories.setText(0, 1, "Customer Notified");
			gridHistories.setText(0, 2, "Status");
			gridHistories.setText(0, 3, "Comments");
			for (int i = 0; i< numHistories; i++)
			{
				OrderStatusHistoryModel history = histories.get(i);
				int row = i+1;
				int k = row % 2;
				String rowStyle = "Even";
				if (k > 0) rowStyle = "Odd";
				gridHistories.getRowFormatter().addStyleName(row, rowStyle);	
				
				gridHistories.setText(row, 0, DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_TIME_SHORT).format(history.getDateAdded()));
				if (history.getNotified()) 
					gridHistories.setWidget(row, 1, new Image(getImageCommonDirectory() + "tick.gif"));
				else
					gridHistories.setWidget(row, 1, new Image(getImageCommonDirectory() + "cross.gif"));
				cf.setHorizontalAlignment(row, 1, HasHorizontalAlignment.ALIGN_CENTER);
				gridHistories.setText(row, 2, history.getStatus());
				gridHistories.setHTML(row, 3, history.getComments());
				cf.setWidth(row, 3, "500px");
			}
			add(gridHistories);

			Label commentLabel = new Label("Comment:");
			commentLabel.setStyleName("Title");
			add(commentLabel);

			TextArea commentTextArea = new TextArea();
			commentTextArea.setCharacterWidth(80);
			commentTextArea.setVisibleLines(10);
			add (commentTextArea);
			elements.put("comment", commentTextArea);

			InlineHTML commentStatusHTML = new InlineHTML("<br/><br/>Status: ");
			commentStatusHTML.setStyleName("Title");
			add(commentStatusHTML);

			List<OrderStatusModel> orderStatusModels = orderStatusComponent.getOrderStatusModels();
			ListBox statusListBox = new ListBox();
			Iterator<OrderStatusModel> iter = orderStatusModels.iterator();
			int i = 0;
			while(iter.hasNext())
			{
				OrderStatusModel model = iter.next();
				statusListBox.addItem(model.getName(), String.valueOf(model.getId()));
				if (orderModel.getStatus().equals(model.getName()))
				{
					statusListBox.setSelectedIndex(i);
				}
				i++;
			}
			add(statusListBox);
			elements.put("orderStatus", statusListBox);

			InlineHTML notifyCustomerHTML = new InlineHTML("<br/><br/>Notify Customer: ");
			notifyCustomerHTML.setStyleName("Title");
			add(notifyCustomerHTML);

			CheckBox notifyCustomerCheckBox = new CheckBox();
			notifyCustomerCheckBox.setValue(true);
			add(notifyCustomerCheckBox);
			elements.put("notifyCustomer", notifyCustomerCheckBox);

			InlineHTML appendCommentHTML = new InlineHTML("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Append Comment to Notification: ");
			appendCommentHTML.setStyleName("Title");
			add(appendCommentHTML);
			CheckBox appendCommentCheckBox = new CheckBox();
			appendCommentCheckBox.setValue(true);
			add(appendCommentCheckBox);
			elements.put("appendComment", appendCommentCheckBox);

			add(new HTML("&nbsp;"));
			Button updateButton = new Button("update", updateHandler);
			updateButton.addStyleName("ComponentLink");
			add(updateButton);
		}

		if (isQuote) {
			List<TermsAndConditionsModel> tandcs = orderModel.getTermsAndConditions();
			int numTandCs = tandcs.size();

			if (numTandCs > 0  || edit) {
				add(new HTML("&nbsp;"));
				Label tandcLabel = new Label("Terms and Conditions");
				tandcLabel.setStyleName("Supertitle");
				add(tandcLabel);
				add(new HTML("&nbsp;"));
			}

			String prevlabel = "";
			for (int i = 0; i< numTandCs; i++)
			{
				TermsAndConditionsModel tandc = tandcs.get(i);
				String label = tandc.getLabel();
				if (!label.equals(prevlabel)) {
					Label tandcLabel = new Label(label);
					tandcLabel.setStyleName("Title");
					add(tandcLabel);
					add(new HTML("&nbsp;"));
					prevlabel = label;
				}
				int numColumns = 1;
				if (edit) numColumns = 2;
				Grid gridTandCs = new Grid(1,numColumns);
				gridTandCs.setHTML(0, 0, tandc.getText());

				if (edit)
				{
					Image deleteIcon = new Image(getImageCommonDirectory() + "delete_icon.gif");
					deleteIcon.setStyleName("ComponentLink");
					deleteIcon.addStyleName("index:" + tandc.getId());
					deleteIcon.addClickHandler(deleteTandCHandler);
					gridTandCs.setWidget(0, 1, deleteIcon);
				}
				add(gridTandCs);

				add(new HTML("&nbsp;"));
								
			}

			if (edit) {
				Button addCatalogProductButton = new Button("add terms and conditions", addTandCHandler);
				add(addCatalogProductButton);
				add(new HTML("&nbsp;"));
			}
		}

		String middleBottomStr = "";
		for (int i = 0; i< 200; i++)
		{
			middleBottomStr += " &nbsp;";
		}
		InlineHTML middleBottomHTML = new InlineHTML(middleBottomStr);
		add(middleBottomHTML);
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	protected ClickHandler editCustomerHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			dialogAddress(EditOrderComponent.EditCustomer);
		}
	};

	protected ClickHandler openEditIntroductionHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			build(true);
		}
	};

	protected ClickHandler cancelEditIntroductionHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			build();
		}
	};

	protected ClickHandler editIntroductionHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			Window.scrollTo(0, 0);
			action = EditOrderComponent.EditIntroduction;
			callback.onSuccess(thisComponent);
		}
	};

	protected ClickHandler editShipToHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			dialogAddress(EditOrderComponent.EditShipTo);
		}
	};

	protected ClickHandler editBillToHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			dialogAddress(EditOrderComponent.EditBillTo);
		}
	};

	protected void dialogAddress(String handlerAction)
	{
		action = handlerAction;

		addressDialogBox = new DialogBox();
		addressDialogBox.setStyleName(getHandle()+ "AddressDialogBox");
		addressDialogBox.addStyleName("DialogBox");
		addressDialogBox.setWidth("400px");
		addressDialogBox.setText("Update Address");

		FlowPanel dialogContents = new FlowPanel();
		int numrows = 2;
		if (action.equals(EditOrderComponent.EditCustomer)) numrows = 4;
		Grid grid = new Grid(numrows,2);

		int numrow = 0;

		ListBox addressListBox = new ListBox();
		addressListBox.addItem("Please Select ...", "0");
		List<AddressModel> addresses = orderModel.getAccountModel().getAddresses();

		Iterator<AddressModel> iter1 = addresses.iterator();
		while(iter1.hasNext())
		{
			AddressModel model = iter1.next();
			String address = "";
			if (orderMetaModel.isDisplayCompany() && model.getCompany() != null && model.getCompany().length() > 0) address += model.getCompany() + ", ";
			address += model.getFirstname() + " " + model.getLastname() + ", ";
			address += model.getStreet() + ", ";
			if (orderMetaModel.isDisplaySuburb())  address += model.getSuburb() + ", ";
			if (orderMetaModel.isDisplayState())
				address += model.getCity() + ", " + model.getState() + " " + model.getPostcode() + ", ";
			else
				address += model.getCity() + ", " + model.getPostcode() + ", ";
			address += model.getCountry();

			addressListBox.addItem(address, String.valueOf(model.getId()));
		}
		elements.put("addressId", addressListBox);
		grid.setText(numrow, 0, "Address:");
		grid.setWidget(numrow, 1, addressListBox);
		numrow++;

		if (action.equals(EditOrderComponent.EditCustomer)) {
			TextBox telephone = new TextBox(); 
			elements.put("telephone", telephone);
			grid.setText(numrow, 0, "Telephone");
			grid.setWidget(numrow, 1, telephone);
			telephone.setText(orderModel.getTelephone());
			numrow++;

			TextBox email = new TextBox(); 
			elements.put("emailAddress", email);
			grid.setText(numrow, 0, "Email Address");
			grid.setWidget(numrow, 1, email);
			email.setText(orderModel.getEmailAddress());
			numrow++;
		}

		dialogContents.add(grid);

		HorizontalPanel buttonPanel = new HorizontalPanel();

		Button closeButton = new Button("close",
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				addressDialogBox.hide();
			}
		});
		buttonPanel.add(closeButton);
		buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

		String editStr = "update";
		Button editButton = new Button(editStr,
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				addressDialogBox.hide();
				callback.onSuccess(thisComponent);
			}
		});
		buttonPanel.add(editButton);
		dialogContents.add(buttonPanel);

		addressDialogBox.setWidget(dialogContents);
		addressDialogBox.center();
		addressDialogBox.show();
		addressListBox.setFocus(true);
	}

	protected ClickHandler deleteProductHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			if (Window.confirm("Delete Product?")) {
				Widget source = (Widget)event.getSource();
				String stylenames = source.getStyleName();
				int loc = stylenames.indexOf("index:");
				stylenames = stylenames.substring(loc+6);
				loc = stylenames.indexOf(" ");
				if (loc > -1) stylenames = stylenames.substring(0, loc);
				int id = Integer.parseInt(stylenames);
				action = EditOrderComponent.DeleteProduct;
				elements.put("orderProductId", new InlineLabel(String.valueOf(id)));
				callback.onSuccess(thisComponent);			
			}
		}
	};

	protected ClickHandler editProductHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int i = Integer.parseInt(stylenames);
			OrderProductModel product = orderModel.getProducts().get(i);
			dialogProduct(product.getId() > 0, product);
		}
	};

	protected ClickHandler addNonCatalogProductHandler = new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			dialogProduct(false, null);
		}
	};

	protected ClickHandler addCatalogProductHandler = new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			dialogProduct(true, null);
		}
	};

	protected ClickHandler updateCatalogProductsToCurrentPricingHandler = new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			action = EditOrderComponent.UpdateCatalogProductsToCurrentPricing;
			callback.onSuccess(thisComponent);
		}
	};

	protected void dialogProduct(boolean isCatalog, OrderProductModel product)
	{
		if (product != null) {
			elements.put("orderProductId", new InlineLabel(String.valueOf(product.getOpId())));
			elements.put("productId", new InlineLabel(String.valueOf(product.getId())));
		}

		if (productDialogBox == null) productDialogBox = new DialogBox();
		else productDialogBox.clear();

		productDialogBox.setStyleName(getHandle()+ "ProductDialogBox");
		productDialogBox.addStyleName("DialogBox");
		productDialogBox.setWidth("400px");
		productDialogBox.setText("Add Product");
		if (product != null)productDialogBox.setText("Update Product");
		FlowPanel dialogContents = new FlowPanel();
		int numrows = 1;
		if (product != null) numrows = 6;
		if (!isCatalog) numrows = 8;
		int numrow = 0;
		Grid grid = new Grid(numrows,2);
		dialogContents.add(grid);

		TextBox productQuantity = new TextBox(); 
		elements.put("productQuantity", productQuantity);
		grid.setText(numrow, 0, "Quantity");
		grid.setWidget(numrow, 1, productQuantity);
		if (product != null) productQuantity.setText(String.valueOf(product.getQuantity()));
		else productQuantity.setText("1");
		numrow++;

		if (product == null && isCatalog) {
			if (component.productSearchComponent == null) {
				component.productSearchComponent = new ProductSearchComponent(productDialogBox, controller, null);
			}
			dialogContents.add(component.productSearchComponent);
			component.productSearchComponent.build(true);
			dialogContents.add(new HTML("&nbsp;"));
		}
		else {
			TextBox productName = new TextBox(); 
			productName.setWidth("600px");
			elements.put("productName", productName);
			grid.setText(numrow, 0, "Name");
			grid.setWidget(numrow, 1, productName);
			if (product != null) productName.setText(product.getName());
			numrow++;

			TextBox productModel = new TextBox(); 
			elements.put("productModel", productModel);
			grid.setText(numrow, 0, "Model");
			grid.setWidget(numrow, 1, productModel);
			if (product != null) productModel.setText(product.getModel());
			numrow++;

			TextBox productPrice = new TextBox(); 
			elements.put("productPrice", productPrice);
			grid.setText(numrow, 0, "Price w/o Options");
			grid.setWidget(numrow, 1, productPrice);
			if (product != null) productPrice.setText(String.valueOf(product.getBasePrice()));
			numrow++;

			int numAttributes = 5;
			if (product != null) numAttributes = product.getAttributes().size();

			if (numAttributes > 0)
			{
				Grid attributesGrid = new Grid(numAttributes+1, 5);
				int colCnt = 0;
				attributesGrid.setText(0, colCnt++, "Name");
				attributesGrid.setText(0, colCnt++, "Value");
				attributesGrid.setText(0, colCnt++, "Prefix");
				attributesGrid.setText(0, colCnt++, "Price");
				if (product != null) attributesGrid.setText(0, colCnt++, "Delete");

				AttributeValueModel attribute = null;
				if (product == null) {
					attribute = new AttributeValueModel();
				}
				for (int j = 0; j< numAttributes; j++)
				{
					if (product != null) {
						attribute = product.getAttributes().get(j);
						attributeRow(attributesGrid, attribute, j+1, true);
					}
					else {
						attributeRow(attributesGrid, attribute, j+1, false);
					}
				}

				grid.setText(numrow, 0, "Options");
				grid.setWidget(numrow, 1, attributesGrid);
				numrow++;
			}

			int numDownloads = 0;
			if (product != null) numDownloads = product.getDownloads().size();

			if (numDownloads > 0)
			{
				Grid downloadsGrid = new Grid(numDownloads+1, 4);
				int colCnt = 0;
				downloadsGrid.setText(0, colCnt++, "Count");
				downloadsGrid.setText(0, colCnt++, "Days");
				downloadsGrid.setText(0, colCnt++, "Filename");
				if (product != null) downloadsGrid.setText(0, colCnt++, "Delete");

				for (int j = 0; j< numDownloads; j++)
				{
					DownloadModel download = product.getDownloads().get(j);
					downloadRow(downloadsGrid, download, j+1);
				}

				grid.setText(numrow, 0, "Downloads");
				grid.setWidget(numrow, 1, downloadsGrid);
				numrow++;
			}
		}

		if (!isCatalog) {
			TextBox productWeight = new TextBox(); 
			elements.put("productWeight", productWeight);
			grid.setText(numrow, 0, "Weight");
			grid.setWidget(numrow, 1, productWeight);
			if (product != null) productWeight.setText(String.valueOf(product.getWeight()));
			numrow++;

			int taxClassId = 0;
			if (product != null) taxClassId = product.getTaxClassId();
			List<TaxClassModel> taxClassModels = taxClassesComponent.getTaxClassModels();
			ListBox taxClassListBox = new ListBox();
			taxClassListBox.addItem("None", "0");
			int tc_i = 0;
			if (0 == taxClassId)
			{
				taxClassListBox.setSelectedIndex(tc_i);
			}
			tc_i++;
			Iterator<TaxClassModel> iter1 = taxClassModels.iterator();
			while(iter1.hasNext())
			{
				TaxClassModel model = iter1.next();
				taxClassListBox.addItem(model.getTitle() + ": " + model.getDescription(), String.valueOf(model.getId()));

				if (model.getId() == taxClassId)
				{
					taxClassListBox.setSelectedIndex(tc_i);
				}
				tc_i++;
			}
			elements.put("taxClassId", taxClassListBox);
			grid.setText(numrow, 0, "Tax Class:");
			grid.setWidget(numrow, 1, taxClassListBox);
			numrow++;
		}

		HorizontalPanel buttonPanel = new HorizontalPanel();
		buttonPanel.setTitle("Button Panel");

		Button closeButton = new Button("close",
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				productDialogBox.hide();
			}
		});
		closeButton.setTitle("close");
		buttonPanel.add(closeButton);
		buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

		String editStr = "add product";
		if (product != null)  editStr = "update product";
		Button editButton = new Button(editStr,
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				productDialogBox.hide();
				action = EditOrderComponent.EditProduct;
				callback.onSuccess(thisComponent);
			}
		});
		editButton.setTitle(editStr);
		buttonPanel.add(editButton);
		dialogContents.add(buttonPanel);

		productDialogBox.setWidget(dialogContents);
		if (!(product == null && isCatalog)) {
			productDialogBox.center();
			productDialogBox.show();
		}
		productQuantity.setFocus(true);
	}

	protected ClickHandler deleteTotalHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			if (Window.confirm("Delete Price Entry?")) {
				Widget source = (Widget)event.getSource();
				String stylenames = source.getStyleName();
				int loc = stylenames.indexOf("index:");
				stylenames = stylenames.substring(loc+6);
				loc = stylenames.indexOf(" ");
				if (loc > -1) stylenames = stylenames.substring(0, loc);
				int id = Integer.parseInt(stylenames);
				action = EditOrderComponent.DeleteTotal;
				elements.put("orderTotalId", new InlineLabel(String.valueOf(id)));
				callback.onSuccess(thisComponent);			
			}
		}
	};

	protected ClickHandler addTotalHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			totalDialogBox = new DialogBox();
			totalDialogBox.setStyleName(getHandle()+ "TotalDialogBox");
			totalDialogBox.addStyleName("DialogBox");
			totalDialogBox.setWidth("400px");
			totalDialogBox.setText("Add Total Entry");
			FlowPanel dialogContents = new FlowPanel();
			Grid grid = new Grid(2,2);

			TextBox totalTitle = new TextBox(); 
			elements.put("totalTitle", totalTitle);
			grid.setText(0, 0, "Title");
			grid.setWidget(0, 1, totalTitle);

			TextBox totalValue = new TextBox(); 
			elements.put("totalValue", totalValue);
			grid.setText(1, 0, "Price");
			grid.setWidget(1, 1, totalValue);

			dialogContents.add(grid);

			HorizontalPanel buttonPanel = new HorizontalPanel();

			Button closeButton = new Button("close",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					totalDialogBox.hide();
				}
			});
			buttonPanel.add(closeButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			Button editButton = new Button("add",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					totalDialogBox.hide();
					action = EditOrderComponent.AddTotal;
					callback.onSuccess(thisComponent);
				}
			});
			buttonPanel.add(editButton);
			dialogContents.add(buttonPanel);

			totalDialogBox.setWidget(dialogContents);
			totalDialogBox.center();
			totalDialogBox.show();
			totalTitle.setFocus(true);
		}
	};



	protected ClickHandler addPaymentHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			paymentDialogBox = new DialogBox();
			paymentDialogBox.setStyleName(getHandle()+ "paymentDialogBox");
			paymentDialogBox.addStyleName("DialogBox");
			paymentDialogBox.setWidth("400px");
			paymentDialogBox.setText("Add payment Entry");
			FlowPanel dialogContents = new FlowPanel();
			Grid grid = new Grid(2,2);

			TextBox paymentComments = new TextBox(); 
			elements.put("paymentComments", paymentComments);
			grid.setText(0, 0, "Comments");
			grid.setWidget(0, 1, paymentComments);

			TextBox paymentAmount = new TextBox(); 
			elements.put("paymentAmount", paymentAmount);
			grid.setText(1, 0, "Amount");
			grid.setWidget(1, 1, paymentAmount);

			dialogContents.add(grid);

			HorizontalPanel buttonPanel = new HorizontalPanel();

			Button closeButton = new Button("close",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					paymentDialogBox.hide();
				}
			});
			buttonPanel.add(closeButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			Button editButton = new Button("add",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					paymentDialogBox.hide();
					action = EditOrderComponent.AddPayment;
					callback.onSuccess(thisComponent);
				}
			});
			buttonPanel.add(editButton);
			dialogContents.add(buttonPanel);

			paymentDialogBox.setWidget(dialogContents);
			paymentDialogBox.center();
			paymentDialogBox.show();
			paymentComments.setFocus(true);
		}
	};

	protected ClickHandler addTotalCouponHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			totalDialogBox = new DialogBox();
			totalDialogBox.setStyleName(getHandle()+ "TotalDialogBox");
			totalDialogBox.addStyleName("DialogBox");
			totalDialogBox.setWidth("400px");
			totalDialogBox.setText("Add/Overwrite Coupon");
			FlowPanel dialogContents = new FlowPanel();
			Grid grid = new Grid(2,2);

			TextBox totalCoupon = new TextBox(); 
			elements.put("coupon_code", totalCoupon);
			grid.setText(0, 0, "Coupon");
			grid.setWidget(0, 1, totalCoupon);

			dialogContents.add(grid);

			HorizontalPanel buttonPanel = new HorizontalPanel();

			Button closeButton = new Button("close",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					totalDialogBox.hide();
				}
			});
			buttonPanel.add(closeButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			Button editButton = new Button("add",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					totalDialogBox.hide();
					action = EditOrderComponent.AddCoupon;
					callback.onSuccess(thisComponent);
				}
			});
			buttonPanel.add(editButton);
			dialogContents.add(buttonPanel);

			totalDialogBox.setWidget(dialogContents);
			totalDialogBox.center();
			totalDialogBox.show();
			totalCoupon.setFocus(true);
		}
	};

	protected ClickHandler updateHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			action = EditOrderComponent.UpdateOrderHistory;
			callback.onSuccess(thisComponent);
		}
	};

	protected ClickHandler deleteTandCHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			if (Window.confirm("Delete Term and Condition?")) {
				Widget source = (Widget)event.getSource();
				String stylenames = source.getStyleName();
				int loc = stylenames.indexOf("index:");
				stylenames = stylenames.substring(loc+6);
				loc = stylenames.indexOf(" ");
				if (loc > -1) stylenames = stylenames.substring(0, loc);
				int id = Integer.parseInt(stylenames);
				action = EditOrderComponent.DeleteTermAndCondition;
				elements.put("tAndCId", new InlineLabel(String.valueOf(id)));
				callback.onSuccess(thisComponent);			
			}
		}
	};

	protected ClickHandler addTandCHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			if (termsAndConditionsDialogBox == null) termsAndConditionsDialogBox = new DialogBox();
			else termsAndConditionsDialogBox.clear();

			termsAndConditionsDialogBox.setStyleName(getHandle()+ "termsAndConditionsDialogBox");
			termsAndConditionsDialogBox.addStyleName("DialogBox");
			termsAndConditionsDialogBox.setWidth("400px");
			termsAndConditionsDialogBox.setText("Add Terms And Conditions");
			FlowPanel dialogContents = new FlowPanel();

			if (component.termsAndConditionsComponent == null) {
				component.termsAndConditionsComponent = new TermsAndConditionsComponent(termsAndConditionsDialogBox, controller, null);
			}
			dialogContents.add(component.termsAndConditionsComponent);
			component.termsAndConditionsComponent.build(true);
			dialogContents.add(new HTML("&nbsp;"));

			HorizontalPanel buttonPanel = new HorizontalPanel();

			Button closeButton = new Button("close",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					termsAndConditionsDialogBox.hide();
				}
			});
			buttonPanel.add(closeButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			Button editButton = new Button("add",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					termsAndConditionsDialogBox.hide();
					action = EditOrderComponent.InsertTermAndCondition;
					callback.onSuccess(thisComponent);
				}
			});
			buttonPanel.add(editButton);
			dialogContents.add(buttonPanel);

			termsAndConditionsDialogBox.setWidget(dialogContents);
		}
	};

	public String getAction() {
		return action;
	}

	public HashMap<String, Widget> getElements() {
		return elements;
	}

	public void attributeRow(Grid attributesGrid, AttributeValueModel attributeValueModel, int rowCnt, boolean isDelete)
	{
		elements.put("attributeOrderProductId-" + rowCnt, new InlineLabel(String.valueOf(attributeValueModel.getAttributeId())));

		int colCnt = 0;

		TextBox attributeName = new TextBox(); 
		attributeName.setWidth("100px");
		elements.put("attributeName-" + rowCnt, attributeName);
		attributesGrid.setWidget(rowCnt, colCnt++, attributeName);
		attributeName.setText(attributeValueModel.getAttributeName());

		TextBox attributeValue = new TextBox(); 
		attributeValue.setWidth("300px");
		elements.put("attributeValue-" + rowCnt, attributeValue);
		attributesGrid.setWidget(rowCnt, colCnt++, attributeValue);
		attributeValue.setText(attributeValueModel.getName());

		ListBox prefixListBox = new ListBox();
		prefixListBox.setWidth("50px");
		prefixListBox.addItem("+");
		prefixListBox.addItem("-");
		if (attributeValueModel.getPrefix().equals("-")) {
			prefixListBox.setSelectedIndex(1);
		}
		else {
			prefixListBox.setSelectedIndex(0);
		}
		elements.put("attributePrefix-" + rowCnt, prefixListBox);
		attributesGrid.setWidget(rowCnt, colCnt++, prefixListBox);

		TextBox optionPriceTextBox = new TextBox();
		optionPriceTextBox.setWidth("75px");
		optionPriceTextBox.setText(String.valueOf(attributeValueModel.getPrice()));
		elements.put("attributePrice-" + rowCnt, optionPriceTextBox);
		attributesGrid.setWidget(rowCnt, colCnt++, optionPriceTextBox);

		if (isDelete) {
			CheckBox attributeDelete = new CheckBox();
			elements.put("attributeDelete-" + rowCnt, attributeDelete);
			attributesGrid.setWidget(rowCnt, colCnt++, attributeDelete);
		}
	}

	public void downloadRow(Grid downloadsGrid, DownloadModel downloadModel, int rowCnt)
	{
		elements.put("downloadOrderProductId-" + rowCnt, new InlineLabel(String.valueOf(downloadModel.getId())));

		int colCnt = 0;

		TextBox downloadCnt = new TextBox(); 
		downloadCnt.setWidth("100px");
		elements.put("downloadCnt-" + rowCnt, downloadCnt);
		downloadsGrid.setWidget(rowCnt, colCnt++, downloadCnt);
		downloadCnt.setText(String.valueOf(downloadModel.getCount()));

		TextBox downloadDays = new TextBox(); 
		downloadDays.setWidth("100px");
		elements.put("downloadDays-" + rowCnt, downloadDays);
		downloadsGrid.setWidget(rowCnt, colCnt++, downloadDays);
		downloadDays.setText(String.valueOf(downloadModel.getDays()));

		TextBox downloadFilename = new TextBox(); 
		downloadFilename.setWidth("100px");
		elements.put("downloadFilename-" + rowCnt, downloadFilename);
		downloadsGrid.setWidget(rowCnt, colCnt++, downloadFilename);
		downloadFilename.setText(downloadModel.getFilename());

		CheckBox downloadDelete = new CheckBox();
		elements.put("downloadDelete-" + rowCnt, downloadDelete);
		downloadsGrid.setWidget(rowCnt, colCnt++, downloadDelete);
	}
}
